package com.example.demo.controller;

import com.example.demo.constant.Constants;
import com.example.demo.model.Blog;
import com.example.demo.model.User;
import com.example.demo.service.BlogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;

    @RequestMapping("/getlist")
    public List<Blog> getBlogList(){
        List<Blog> list = blogService.getBlogList();
        if(list != null){
            for (Blog blog: list) {
                String content = blog.getContent();
                if(content!= null && content.length() > 50){
                    content = content.substring(0,50)+"...";
                    blog.setContent(content);
                }
            }
        }
        return list;
    }

    @RequestMapping("/getBlogDetail")
    public Blog getBlogDetail(Integer blogId,HttpServletRequest request){
        Blog blog = blogService.getBlogDetail(blogId);
        //判断作者是否是登录用户
        User user = (User) request.getSession(false).getAttribute(Constants.SESSION_USER_INFO);
        if (blog!=null && user !=null && blog.getUserId()==user.getId()){
            blog.setLoginUser(1);
        }
        return blog;
    }

    @RequestMapping("/add")
    public boolean addBlog(Blog blog, HttpServletRequest request){
        User user = (User)request.getSession(false).getAttribute(Constants.SESSION_USER_INFO);
        if(user == null || user.getId()<0){
            return false;
        }
        blog.setUserId(user.getId());
        Integer num = blogService.insert(blog);
        return num == 1;
    }

    @RequestMapping("/update")
    public boolean update(Blog blog){
        Integer num = blogService.update(blog);
        return num == 1;
    }

    @RequestMapping("/delete")
    public boolean delete(Integer blogId){
        Integer num = blogService.delete(blogId);
        return num == 1;
    }
}
